// 获取当前日期是今年的第几周
function getWeekNumber(date) {
  const oneJan = new Date(date.getFullYear(), 0, 1);
  const numberOfDays = Math.floor((date - oneJan) / (24 * 60 * 60 * 1000));
  return Math.ceil((numberOfDays + oneJan.getDay() + 1) / 7);
}

// 根据日期计算需要执行的换位次数
function calculateExchangeCount() {
  const today = new Date(); // 注释掉原代码
  //const today = new Date(new Date().getFullYear(), 10, 9); // 设置为9月14日方便测试
  const startYear = today.getFullYear();
  
  // 9月14日作为起始日期
  const startDate = new Date(startYear, 8, 14); // 月份从0开始，所以8代表9月
  // 如果当前日期在9月14日之前，返回0
  const startWeek = getWeekNumber(startDate);
  const currentWeek = getWeekNumber(today);
  const weekDiff = currentWeek - startWeek;

  console.log(weekDiff)
  
  if (today < startDate) {
    return 0;
  }
  
  // 计算当前日期与起始日期之间的周数差

  
  
  // 每两周增加一次换位次数
  return Math.max(0, Math.floor(weekDiff / 2) + 1);
}

// 执行多次换位计算
function performMultipleExchanges(seatData, count) {
  let currentSeatData = seatData;
  for (let i = 0; i < count; i++) {
    currentSeatData = exchangeSeats(currentSeatData);
  }
  return currentSeatData;
}

// 默认座位数据
const defaultSeatData = [
    [
    ["梁xr","彭xf"],
    ["蔡yt","周xr"],
    ["李xq","焦jh"],
    ["卢qy","李xy"],
    ["佘yy","林zq"],
    ["代jh","王jj"]
    ],

    [
    ["何xh","宋yc"],
    ["杨sh","张yj"],
    ["徐xm","李yf"],
    ["杨zl","王yd"],
    ["yp","吴hn"],
    ["阿mqt","吴rj"]
    ],
    [
    ["周yt","莫yt"],
    ["贾sq","刘yr"],
    ["张yc","柏cx"],
    ["周be","胡zy"],
    ["殷mk","曾zr"],
    ["袁zc","黄hy"]
    ],
    [
    ["王jh","向hh"],
    ["李yx","王sc"],
    ["饶bw","黄sh"],
    ["肖hl","陈吉sq"],
    ["宋bh","王yb"],
    ["none","none"]
    ]
];

// 读取配置文件
fetch('./config.json')
  .then(response => response.json())
  .then(data => {
    const seatData = data.seat;
    displaySeats(seatData);
    
    // 计算需要执行的换位次数
    const exchangeCount = calculateExchangeCount();

    // 如果需要执行换位计算
    if (exchangeCount > 0) {
      const newSeatData = performMultipleExchanges(seatData, exchangeCount);
      displaySeats(newSeatData, true);
    }
  })
  .catch(error => {
    console.error('读取配置文件时出错，使用默认数据:', error);
    // 使用默认座位数据
    displaySeats(defaultSeatData);
    
    // 计算需要执行的换位次数
    const exchangeCount = calculateExchangeCount();

    // 如果需要执行换位计算
    if (exchangeCount > 0) {
      const newSeatData = performMultipleExchanges(defaultSeatData, exchangeCount);
      displaySeats(newSeatData, true);
    }
  });

// 显示座位函数
function displaySeats(seatData, isExchanged = false) {
  const container = document.getElementById('seat-container');
  
  // 清空容器
  container.innerHTML = '';
  
  // 遍历每一排
  for (let row = 0; row < seatData[0].length; row++) {
    // 创建排容器
    const rowElement = document.createElement('div');
    rowElement.className = 'seat-row';
    
    // 添加初始动画状态
    rowElement.style.opacity = '0';
    rowElement.style.transform = 'translateY(30px)';
    rowElement.style.transition = 'opacity 0.5s ease-out, transform 0.5s ease-out';
    
    // 延迟触发每排的动画
    setTimeout(() => {
      rowElement.style.opacity = '1';
      rowElement.style.transform = 'translateY(0)';
    }, row * 100 + 400);
    
    // 遍历每一列
    for (let col = 0; col < seatData.length; col++) {
      const deskGroup = seatData[col][row];
      
      const deskElement = document.createElement('div');
      deskElement.className = 'desk-group';
      
      // 检查是否为none座位
      if (deskGroup[0] === 'none') {
        deskElement.classList.add('none');
      }
      
      // 添加两个学生名字
      deskGroup.forEach((name, index) => {
        const nameElement = document.createElement('div');
        nameElement.className = 'student-name';
        
        // 检查是否为none
        if (name === 'none') {
          nameElement.textContent = '固定位';
          nameElement.classList.add('none');
        } else {
          nameElement.textContent = name;
        }
        
        deskElement.appendChild(nameElement);
      });
      
      rowElement.appendChild(deskElement);
    }
    
    container.appendChild(rowElement);
  }
}

// 换座位算法
function exchangeSeats(seatData) {
  // 深拷贝座位数据
  const newSeatData = JSON.parse(JSON.stringify(seatData));
  
  // 遍历原始座位数据
  for (let colIndex = 0; colIndex < seatData.length; colIndex++) {
    for (let deskIndex = 0; deskIndex < seatData[colIndex].length; deskIndex++) {
      const deskGroup = seatData[colIndex][deskIndex];
      
      // 检查是否为none座位
      if (deskGroup[0] !== 'none') {
        // 计算新位置 (向右上方移动)
        let newColIndex = (colIndex + 1) % seatData.length;
        let newDeskIndex = (deskIndex - 1 + seatData[colIndex].length) % seatData[colIndex].length;
        
        // 检查新位置是否为none，如果是则继续寻找
        let attempts = 0;
        while (attempts < 200) {
          if (seatData[newColIndex][newDeskIndex][0] !== 'none') {
            // 找到有效位置，移动学生
            newSeatData[newColIndex][newDeskIndex] = [...deskGroup];
            break;
          }
          
          // 继续向右上方移动
          newColIndex = (newColIndex + 1) % seatData.length;
          newDeskIndex = (newDeskIndex - 1 + seatData[newColIndex].length) % seatData[newColIndex].length;
          attempts++;
        }
        
        // 如果尝试200次仍未找到有效位置，抛出错误
        if (attempts >= 200) {
          throw new Error('无法找到有效的座位位置');
        }
      }
    }
  }
  
  return newSeatData;
}

!function () {
    function n(n, e, t) {
        return n.getAttribute(e) || t
    }
 
    function e(n) {
        return document.getElementsByTagName(n)
    }
 
    function t() {
        var t = e("script"), o = t.length, i = t[o - 1];
        return {l: o, z: n(i, "zIndex", -1), o: n(i, "opacity", .5), c: n(i, "color", "0,0,0"), n: n(i, "count",150)}
    }
 
    function o() {
        a = m.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, c = m.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    }
 
    function i() {
        r.clearRect(0, 0, a, c);
        var n, e, t, o, m, l;
        s.forEach(function (i, x) {
            for (i.x += i.xa, i.y += i.ya, i.xa *= i.x > a || i.x < 0 ? -1 : 1, i.ya *= i.y > c || i.y < 0 ? -1 : 1, r.fillRect(i.x - .5, i.y - .5, 1, 1), e = x + 1; e < u.length; e++) n = u[e], null !== n.x && null !== n.y && (o = i.x - n.x, m = i.y - n.y, l = o * o + m * m, l < n.max && (n === y && l >= n.max / 2 && (i.x -= .03 * o, i.y -= .03 * m), t = (n.max - l) / n.max, r.beginPath(), r.lineWidth = t / 2, r.strokeStyle = "rgba(" + d.c + "," + (t + .2) + ")", r.moveTo(i.x, i.y), r.lineTo(n.x, n.y), r.stroke()))
        }), x(i)
    }
 
    var a, c, u, m = document.createElement("canvas"), d = t(), l = "c_n" + d.l, r = m.getContext("2d"),
        x = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (n) {
            window.setTimeout(n, 1e3 / 45)
        }, w = Math.random, y = {x: null, y: null, max: 2e4};
    m.id = l, m.style.cssText = "position:fixed;top:0;left:0;z-index:" + d.z + ";opacity:" + d.o, e("body")[0].appendChild(m), o(), window.onresize = o, window.onmousemove = function (n) {
        n = n || window.event, y.x = n.clientX, y.y = n.clientY
    }, window.onmouseout = function () {
        y.x = null, y.y = null
    };
    for (var s = [], f = 0; d.n > f; f++) {
        var h = w() * a, g = w() * c, v = 2 * w() - 1, p = 2 * w() - 1;
        s.push({x: h, y: g, xa: v, ya: p, max: 6e3})
    }
    u = s.concat([y]), setTimeout(function () {
        i()
    }, 100)
}();

// 显示当前日期
function displayCurrentDate() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    
    const dateDisplayElement = document.querySelector('.date-display');
    if (dateDisplayElement) {
        dateDisplayElement.textContent = `${year}年${month}月${day}日座位表`;
        dateDisplayElement.style.fontSize = 'small';
        dateDisplayElement.style.color = 'gray';
        dateDisplayElement.style.textAlign = 'center';
        dateDisplayElement.style.marginBottom = '10px';
    }
}

// 页面加载完成后显示日期
window.addEventListener('DOMContentLoaded', displayCurrentDate);

// 句子轮播功能
let sentences = [];
let currentSentenceIndex = 0;

// 从sentences.json加载句子
fetch('./sentences.json')
  .then(response => response.json())
  .then(data => {
    sentences = data;
    displayRandomSentence(); // 立即显示第一个句子
    setInterval(displayRandomSentence, 5000); // 每5秒轮播一次
  })
  .catch(error => {
    console.error('读取句子文件时出错:', error);
  });

// 显示随机句子
function displayRandomSentence() {
  if (sentences.length === 0) return;
  
  const sentenceDisplayElement = document.getElementById('sentence-display');
  if (sentenceDisplayElement) {
    // 生成一个随机索引（不重复显示当前句子）
    let newIndex;
    do {
      newIndex = Math.floor(Math.random() * sentences.length);
    } while (newIndex === currentSentenceIndex && sentences.length > 1);
    
    currentSentenceIndex = newIndex;
    const sentence = sentences[currentSentenceIndex];
    
    // 格式化显示内容：- 句子内容 —— 出处 -
    sentenceDisplayElement.textContent = `- ${sentence.context} —— ${sentence.source} -`;
  }
}
